/**
 * Created by dongasai on 16-10-7.
 */
class LoadJS{
    constructor($config){
        this.queue=[];
        this.already={};//已经加载过的
        this.ready={};
        this.configing($config)
        this.head = document.getElementsByTagName('head');
    }
    configing($config){
        this.base=$config.base;
        if(typeof $config.module === 'undefined'){
            this.modules={};
        }else{
            this.modules=$config.module;
        }
    }
    all($list,$name='re'){
        for(let li in  $list) {
            this.one($list[li]);
        }
        let $name2=$name;
        this.queue.push($name);
    }
    /**
     * 加载一个扩展 并且只加载一次
     * @param $name
     */
    one($name){
        let $this=this;
        if(this.already[$name]===true){
            //这个资源已经加载了一次了
            console.log('这个资源已经加载了一次了:',$name);
            return;
        }
        let scriptobj;
        if(typeof this.modules[$name] === 'undefined'){
            //没有定义该扩展
             scriptobj=this.analysis($name);
        }else{
            //扩展已经定义
             scriptobj=this.modules[$name];
        }
        let srcpat=this.srcpat(scriptobj);
        //动态加载
        let scriptsq = document.createElement("SCRIPT");
        scriptsq.typ = "text/javascript";
        // scriptsq.defer = "defer";
        scriptsq.src = srcpat;//设置路径

        scriptsq.addEventListener('load',function(){$this.onload(this)});
        scriptsq.className='';
        LoadJS.addClass(scriptsq,'RequireJS');//设置代表加载中的 class
        this.head[0].appendChild(scriptsq);
        this.already[$name]=true;
    }
    onload(thisob){
        LoadJS.removeClass(thisob,'RequireJS');
        //减掉这个class
        let x =document.getElementsByClassName('RequireJS');
        if(x.length === 0){
            console.log('全部加载完成!!')
            this.loadok();
        }
    }
    loadok(){
        console.log('loadok',this);
        for(let li in this.queue){
            if(typeof this.ready[this.queue[li]] === 'undefined'){
                //没有定义就继续走
                console.log(this.queue[li]+'没有后续方法!');
            }else{
                this.ready[this.queue[li]].call();
            }
        }
    }
    analysis($name){
        let obj={
            'Require_base':false,//从base路径加载 默认为 true
            'src':this.base+$name
        }

        return obj;
    }
    srcpat(obj){
        if(obj.Require_base){
            //从base加载
            return this.base+obj.src;
        }else{
            //不从 base加载
            return obj.src;
        }
    }
     static hasClass(obj, cls) {
        return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    }
    static addClass(obj, cls) {
        if (!LoadJS.hasClass(obj, cls)) obj.className += " " + cls;
    }
    static removeClass(obj, cls) {
        if (LoadJS.hasClass(obj, cls)) {
            var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
            obj.className = obj.className.replace(reg, ' ');
        }
    }
}